package server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

import static constants.SocketConstants.*;

/**
 * @author srh
 * @date 2020/10/18
 **/
public class BIOServer {

    public static void main(String[] args) throws IOException {
        // 创建socket
        ServerSocket serverSocket = new ServerSocket();
        serverSocket.bind(new InetSocketAddress(LOCAL_HOST, PORT));

        while (true) {
            final Socket socket = serverSocket.accept();
            new Thread(() -> {
                try {
                    byte[] buffer = new byte[BUFFER_BYTES];
                    int readLength = socket.getInputStream().read(buffer);
                    // read message
                    System.out.println("server read message: " + new String(buffer, 0, readLength));
                    // write
                    socket.getOutputStream().write(buffer, 0, readLength);
                    socket.getOutputStream().flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
